//
//  Hwi.m
//  Hwi_Library_Demo
//
//  Created by Jeonghwi Kim on 13. 7. 5..
//  Copyright (c) 2013년 KDML. All rights reserved.
//

#import "Hwi.h"


@implementation Postoffice_item
@end



@interface Hwi ()
@property (weak,nonatomic) id<Hwi_Delegate> delegate;
@property (strong,nonatomic) NSMutableData *data_for_network_01;
@property (strong,nonatomic) NSMutableData *data_for_network_02;
@property (strong,nonatomic) NSMutableData *data_for_network_03;
@property (strong,nonatomic) NSMutableData *data_for_network_04;
@property (strong,nonatomic) NSMutableData *data_for_network_05_post_office;
@property (strong,nonatomic) NSString *log_id;
@property (strong,nonatomic) NSURLConnection *conn_01;
@property (strong,nonatomic) NSURLConnection *conn_02;
@property (strong,nonatomic) NSURLConnection *conn_03;
@property (strong,nonatomic) NSURLConnection *conn_04;
@property (strong,nonatomic) NSURLConnection *conn_05_postoffice;

@property (strong, nonatomic) NSTimer *timer_for_network_check01;
@property (strong, nonatomic) NSTimer *timer_for_network_check02;
@property (strong, nonatomic) NSTimer *timer_for_network_check03;
@property (strong, nonatomic) NSTimer *timer_for_network_check04;

@property (strong, nonatomic) void (^complete03)(NSDictionary *dic);
@property (strong, nonatomic) void (^complete04)(NSDictionary *dic);
@property (strong, nonatomic) void (^complete05)(NSDictionary *dic);


@property (strong, nonatomic) NSMutableArray *array01_post_office;
@property (strong, nonatomic) Postoffice_item *postoffice_item;

@property BOOL is_xml_parser_address;
@property BOOL is_xml_parser_postcd;

@property (strong , nonatomic) UIView *view01_01_for_progress_container;
@property (strong , nonatomic) UIView *view01_02_for_progress_round;
@property (strong , nonatomic) UIActivityIndicatorView *view01_03_acti_indi;
@property (strong , nonatomic) UILabel *view01_04_label_loading;


@property (strong,nonatomic) CLLocationManager *location_manager;
@end






@implementation Hwi




+(id)get_instance
{
    static Hwi *singltone;
    if(!singltone)
    {
        singltone = [[Hwi alloc] init];
    }
    return singltone;
}




- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int code = [httpResponse statusCode];
    if(  [connection isEqual:self.conn_01] ||  [connection isEqual:self.conn_02]||  [connection isEqual:self.conn_03]||  [connection isEqual:self.conn_04] )
    {
        NSLog(@"Hwi_Lib : JSON Network  log_id : %@   ,  response_code : %d",self.log_id,code);
    }
    else if( [connection isEqual:self.conn_05_postoffice] )
    {
        NSLog(@"Hwi_Lib : POST Office response code : %d",code);
    }
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    if([connection isEqual:self.conn_01])
    {
        if(!self.data_for_network_01)
        {
            self.data_for_network_01 = [[NSMutableData alloc] init];
        }
        
        [self.data_for_network_01 appendData:data];
    }
    else if([connection isEqual:self.conn_02])
    {
        if(!self.data_for_network_02)
        {
            self.data_for_network_02 = [[NSMutableData alloc] init];
        }
        
        [self.data_for_network_02 appendData:data];
    }
    else if([connection isEqual:self.conn_03])
    {
        if(!self.data_for_network_03)
        {
            self.data_for_network_03 = [[NSMutableData alloc] init];
        }
        
        [self.data_for_network_03 appendData:data];
    }
    else if([connection isEqual:self.conn_04])
    {
        if(!self.data_for_network_04)
        {
            self.data_for_network_04 = [[NSMutableData alloc] init];
        }
        
        [self.data_for_network_04 appendData:data];
    }
    else if([connection isEqual:self.conn_05_postoffice])
    {
        if(!self.data_for_network_05_post_office)
        {
            self.data_for_network_05_post_office = [[NSMutableData alloc] init];
        }
        
        [self.data_for_network_05_post_office appendData:data];
    }
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    

    [self.timer_for_network_check01 invalidate];
    [self.timer_for_network_check02 invalidate];
    [self.timer_for_network_check03 invalidate];
    [self.timer_for_network_check04 invalidate];
    
    
    if([connection isEqual:self.conn_01]  ||  [connection isEqual:self.conn_02]||  [connection isEqual:self.conn_03]||  [connection isEqual:self.conn_04])
    {
        NSMutableData *data;
        if([connection isEqual:self.conn_01])
        {
            data = self.data_for_network_01;
        }
        else if([connection isEqual:self.conn_02])
        {
            data = self.data_for_network_02;
        }
        else if([connection isEqual:self.conn_03])
        {
            data = self.data_for_network_03;
        }
        else if([connection isEqual:self.conn_04])
        {
            data = self.data_for_network_04;
        }
        
        NSDictionary *dic_result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSString *string_data = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Hwi_Lib : response : string : \n\n%@\n\n",string_data);
        if( [connection isEqual:self.conn_03]||  [connection isEqual:self.conn_04])
        {
            
            if(dic_result)
            {
                if([connection isEqual:self.conn_03])
                {
                    self.complete03(dic_result);
                }
                else if([connection isEqual:self.conn_04])
                {
                    self.complete04(dic_result);
                }
                
            }
            else
            {
                NSLog(@"Hwi_Lib : ERROR : JSON return fail");
                NSLog(@"Hwi_Lib : ERROR : string : %@",string_data);
            }
        }
        else
        {
            if(dic_result)
            {
                if(self.delegate)
                {
                    [self.delegate hwi02_did_receive_data_from_json_network:dic_result string_data:string_data log_id:self.log_id];
                }
            }
            else
            {
                NSLog(@"Hwi_Lib : ERROR : JSON return fail");
                NSLog(@"Hwi_Lib : ERROR : string : %@",string_data);
            }
        }
        
        
        
        
    }
    else if([connection isEqual:self.conn_05_postoffice])
    {
        NSString *result_string = [[NSString alloc] initWithData:self.data_for_network_05_post_office encoding:NSEUC_KR_ENCODING];
        
        NSLog(@"로그 01 UTF8 : %@",result_string);
        NSXMLParser *parser_for_postoffice = [[NSXMLParser alloc] initWithData:self.data_for_network_05_post_office];
        [parser_for_postoffice setDelegate:self];
        [parser_for_postoffice parse];
        
    }
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"didStartElement  elementName : %@",elementName);
    
    self.is_xml_parser_address=NO;
    self.is_xml_parser_postcd=NO;
    if([elementName isEqualToString:@"itemlist"])
    {
        if(!self.array01_post_office)
            self.array01_post_office = [[NSMutableArray alloc] init];
        else
            [self.array01_post_office removeAllObjects];
    }
    else if([elementName isEqualToString:@"item"])
    {
        self.postoffice_item = [[Postoffice_item alloc] init];
    }
    else if([elementName isEqualToString:@"address"])
    {
        self.is_xml_parser_address = YES;
    }
    else if([elementName isEqualToString:@"postcd"])
    {
        self.is_xml_parser_postcd = YES;
    }
    
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    
    if(self.is_xml_parser_postcd)
    {
        self.postoffice_item.string01_post_cd=string;
    }
    
}


- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    
    if(self.is_xml_parser_address)
    {
        self.postoffice_item.string02_address = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    
    if([elementName isEqualToString:@"itemlist"])
    {
        [self.delegate hwi04_did_receive_postoffice_network:self.array01_post_office];
    }
    else if([elementName isEqualToString:@"item"])
    {
        [self.array01_post_office addObject:self.postoffice_item];
    }
    else if([elementName isEqualToString:@"address"])
    {
        self.is_xml_parser_address = NO;
    }
    else if([elementName isEqualToString:@"postcd"])
    {
        self.is_xml_parser_postcd = NO;
    }
}




- (void)locationManager:(CLLocationManager *)manager
	 didUpdateLocations:(NSArray *)locations
{
    [manager stopUpdatingLocation];
    CLLocation *location_ =[locations lastObject];
    
    NSString *lat = [NSString stringWithFormat:@"%f",location_.coordinate.latitude];
    NSString *lon = [NSString stringWithFormat:@"%f",location_.coordinate.longitude];
    
    
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location_ completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        NSString *address_string = [[NSString alloc] initWithFormat:@"%@ %@ %@ %@ %@ %@", placemark.administrativeArea, placemark.subAdministrativeArea ?placemark.subAdministrativeArea:@"", placemark.locality?placemark.locality:@"", placemark.subLocality?placemark.subLocality:@"", placemark.thoroughfare?placemark.thoroughfare:@"", placemark.subThoroughfare?placemark.subThoroughfare:@""];
        address_string = [address_string stringByReplacingOccurrencesOfString:@"  " withString:@" "];
        
        
        [self.delegate hwi07_did_update_location:manager locations:locations latitude:lat lon:lon address:address_string];
        NSDictionary *oneDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                locations,@"locations",
                                lat,@"latitude",
                                lon,@"longitude",
                                address_string,@"address_string",
                                nil];
        if(self.complete05)
        self.complete05(oneDic);
    }];
    
    
}


-(void)on_network_fail:(NSTimer*)timer
{
    
    [[[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Please check Network" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
    if([[timer userInfo] isEqual:self.conn_01])
    {
        
    }
    else if([[timer userInfo] isEqual:self.conn_02])
    {
        
    }
    else if([[timer userInfo] isEqual:self.conn_03])
    {
        
    }
    else if([[timer userInfo] isEqual:self.conn_04])
    {
        
    }

}






-(NSString*)hwi01_add_comma:(NSString*)number
{
    
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
    
    NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:[number intValue]]];
    
    return formatted;
}

-(void)hwi02_json_network_url:(NSString*)url parameter_dic:(NSDictionary*)params method:(NSString*)method callback:(id<Hwi_Delegate>)callback log_id:(NSString*)log_id is_second_try_for_same_time:(BOOL)is_second
{
    
    
    self.delegate = callback;
    self.log_id = log_id;
    NSMutableURLRequest *request;
    if(params)
    {
        
        NSMutableArray *array_for_param = [[NSMutableArray alloc] init];
        
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [array_for_param addObject:[NSString stringWithFormat:@"%@=%@",key,obj]];
        }];
        
        NSString *params_string= [array_for_param componentsJoinedByString:@"&"];
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",url,params_string]]];
        
        if( !([method isEqualToString:@"GET"] || [method isEqualToString:@"get"]) )
        {
            [request setHTTPBody:[params_string dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        
    }
    else
    {
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    }
    
    [request setHTTPMethod:method];
    
    if(!is_second)
    {
        self.data_for_network_01 = nil;
        self.conn_01 = [NSURLConnection connectionWithRequest:request delegate:self];
        self.timer_for_network_check01 =  [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(on_network_fail:) userInfo:self.conn_01 repeats:NO];
    }
    else
    {
        self.data_for_network_02 = nil;
        self.conn_02 = [NSURLConnection connectionWithRequest:request delegate:self];
        self.timer_for_network_check02 = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(on_network_fail:) userInfo:self.conn_02 repeats:NO];
    }
    
}


-(void)hwi02_json_network_url:(NSString *)url parameter_dic:(NSDictionary *)params method:(NSString *)method log_id:(NSString *)log_id is_second_try_for_same_time:(BOOL)is_second with_block:(void (^)(NSDictionary *dic))complete
{


    self.log_id = log_id;
    if(!is_second)
    {
        self.complete03 = complete;
    }
    else
    {
        self.complete04 = complete;
    }
    
    NSMutableURLRequest *request;
    if(params)
    {
        
        NSMutableArray *array_for_param = [[NSMutableArray alloc] init];
        
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [array_for_param addObject:[NSString stringWithFormat:@"%@=%@",key,obj]];
        }];
        
        NSString *params_string= [array_for_param componentsJoinedByString:@"&"];
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",url,params_string]]];
        
        if( !([method isEqualToString:@"GET"] || [method isEqualToString:@"get"]) )
        {
            [request setHTTPBody:[params_string dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        
    }
    else
    {
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    }
    
    [request setHTTPMethod:method];
    
    if(!is_second)
    {

        self.data_for_network_03 = nil;
        self.conn_03 = [NSURLConnection connectionWithRequest:request delegate:self];
        self.timer_for_network_check03 =[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(on_network_fail:) userInfo:self.conn_03 repeats:NO];
    }
    else
    {

        self.data_for_network_04 = nil;
        self.conn_04 = [NSURLConnection connectionWithRequest:request delegate:self];
        self.timer_for_network_check04 =[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(on_network_fail:) userInfo:self.conn_04 repeats:NO];
    }

    
}


-(BOOL)hwi03_is_valid_email:(NSString *)emailString
{
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    
    NSString *emailRegex = stricterFilterString ;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:emailString];
}

-(void)hwi04_get_address_from_postoffice_with_string:(NSString*)input_address and_postOffice_api_key:(NSString*)api_key callback:(id<Hwi_Delegate>)callback
{
    self.delegate =callback;
    if(!api_key)
    {
        api_key = @"861394877e6c97c4e1346297408364";
    }
    
    NSString *api_url =[NSString stringWithFormat:@"http://biz.epost.go.kr/KpostPortal/openapied?regkey=%@&target=post&query=%@",api_key,[input_address stringByAddingPercentEscapesUsingEncoding:NSEUC_KR_ENCODING]];
    NSLog(@"api_url  : %@",api_url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:api_url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"ko" forHTTPHeaderField:@"accept-language"];
    self.data_for_network_05_post_office = nil;
    NSLog(@"request allHTTPHeaderFields info : %@",request.allHTTPHeaderFields);
    
    self.conn_05_postoffice = [NSURLConnection connectionWithRequest:request delegate:self];
    
    
}


-(BOOL)hwi05_is_contain_string:(NSString*)string query_string:(NSString*)string_word
{
    if([string rangeOfString:string_word].location != NSNotFound)
        return YES;
    else
        return NO;
}


-(NSDictionary*)hwi06_get_now_is_ko_KR:(BOOL)you_want_korea_time
{
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if(you_want_korea_time)
    {
        NSLocale *locale               = [[NSLocale alloc] initWithLocaleIdentifier:@"ko_KR"];
        [dateFormatter setLocale:locale];
    }
    
    [dateFormatter setDateFormat:@"yyyy"];
    int nYear = [[dateFormatter stringFromDate:today] intValue];
    
    [dateFormatter setDateFormat:@"MM"];
    int nMonth = [[dateFormatter stringFromDate:today] intValue];
    
    [dateFormatter setDateFormat:@"dd"];
    
    int nDay = [[dateFormatter stringFromDate:today] intValue];
    
    [dateFormatter setDateFormat:@"HH"];
    NSString *nCurTime_hour = [dateFormatter stringFromDate:today];
    [dateFormatter setDateFormat:@"mm"];
    NSString *nCurTime_minute = [dateFormatter stringFromDate:today];
    [dateFormatter setDateFormat:@"ss"];
    NSString *nCurTime_second = [dateFormatter stringFromDate:today];
    
    
    NSString *month;
    if(nMonth<10)
    {
        month = [NSString stringWithFormat:@"0%d",nMonth];
    }
    else
    {
        month = [NSString stringWithFormat:@"%d",nMonth];
    }
    
    NSString *day;
    if(nDay<10)
    {
        day = [NSString stringWithFormat:@"0%d",nDay];
    }
    else
    {
        day = [NSString stringWithFormat:@"%d",nDay];
    }
    
    
    NSDictionary *result_dic = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"%d",nYear],@"year",
                                [NSString stringWithFormat:@"%d",nMonth],@"month_int",
                                [NSString stringWithFormat:@"%@",month],@"month",
                                [NSString stringWithFormat:@"%d",nDay],@"day_int",
                                [NSString stringWithFormat:@"%@",day],@"day",
                                [NSString stringWithFormat:@"%@",nCurTime_hour],@"hour",
                                [NSString stringWithFormat:@"%@",nCurTime_minute],@"minute",
                                [NSString stringWithFormat:@"%@",nCurTime_second],@"second",
                                
                                nil];
    
    
    NSLog(@"result_dic : %@",result_dic);
    return result_dic;
}

-(NSString*)hwi06_get_date_with_type:(int)type string:(NSString*)date_string
{
    NSString *result_string;
    
    NSString *year = [date_string substringToIndex:4];
    NSString *month = [date_string substringWithRange:NSMakeRange(4, 2)];
    NSString *date = [date_string substringWithRange:NSMakeRange(6, 2)];
    
    
    switch (type) {
        case 0:
            result_string = [NSString stringWithFormat:@"%@-%@-%@",year,month,date];
            break;
        case 1:
            result_string = [NSString stringWithFormat:@"%@년 %@월 %@일",year,month,date];
            break;
            
        default:
            break;
    }
    NSLog(@"result_string : %@",result_string);
    return result_string;
}

-(void)hwi07_get_current_location_with_callback:(id<Hwi_Delegate>)callback
{
    if(!self.location_manager)
    {
        self.location_manager = [[CLLocationManager alloc] init];
    }
    self.delegate = callback;
    self.location_manager.delegate = self;
    self.location_manager.distanceFilter = kCLDistanceFilterNone;
    self.location_manager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.location_manager startUpdatingLocation];
}

-(void)hwi07_get_current_location_with_block:(void (^)(NSDictionary *dic))complete
{
    if(!self.location_manager)
    {
        self.location_manager = [[CLLocationManager alloc] init];
    }
    self.complete05 = complete;
    self.location_manager.delegate = self;
    self.location_manager.distanceFilter = kCLDistanceFilterNone;
    self.location_manager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.location_manager startUpdatingLocation];
}


-(void)hwi08_show_progress_bar:(UIView*)parent_view
{
    UIView *view_for_progress;
    for(UIView *v in [parent_view subviews])
    {
        if([v.restorationIdentifier isEqualToString:@"hwi_progress_indicator"])
        {
            view_for_progress =v;
        }
    }
    
    [parent_view bringSubviewToFront:view_for_progress];
    
    if(!view_for_progress)
    {
        // 전체화면 크기의 배경 뷰
        view_for_progress = [[UIView alloc] initWithFrame:CGRectMake(0, 0, parent_view.frame.size.width, parent_view.frame.size.height)];
        [view_for_progress setRestorationIdentifier:@"hwi_progress_indicator"];
        
        view_for_progress.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
        
        [parent_view addSubview:view_for_progress];
        
        CGFloat short_size;
        CGFloat large_size;
        if( parent_view.frame.size.height > parent_view.frame.size.width)
        {
            short_size =parent_view.frame.size.width;
            large_size =parent_view.frame.size.height;
        }
        else
        {
            short_size =parent_view.frame.size.height;
            large_size =parent_view.frame.size.width;
        }
        
        // 다이얼로그 생성
        CGSize round_size = CGSizeMake(short_size*(5.0/11.0) , short_size*(5.0/11.0));
        UIView *view_for_round = [[UIView alloc] initWithFrame:CGRectMake((parent_view.frame.size.width-round_size.width)/2,(parent_view.frame.size.height-round_size.height)/2 , round_size.width,round_size.height )];
        
        
        [view_for_round setBackgroundColor:[UIColor blackColor]];
        view_for_round.layer.cornerRadius = 15.0;
        [view_for_progress addSubview:view_for_round];
        
        UILabel *label_loading = [[UILabel alloc] initWithFrame:CGRectMake(0, round_size.height*(7.0/11.0), round_size.width, round_size.height*(4.0/11.0))];
        label_loading.text =  NSLocalizedString(@"progress_indicator_message", @"Please add NSLocalizedString -> progress_indicator_message");
        label_loading.textColor = [UIColor whiteColor];
        label_loading.backgroundColor = [UIColor clearColor];
        label_loading.textAlignment = NSTextAlignmentCenter;
        
        [view_for_round addSubview:label_loading];
        
        UIActivityIndicatorView *acti_indi = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        
        [acti_indi setFrame:CGRectMake( (round_size.width - 50)/2 , (round_size.height - 50)/2 , 50, 50)];
        [acti_indi setHidden:NO];
        [acti_indi startAnimating];
        [view_for_round addSubview:acti_indi];
        
    }
    
    [view_for_progress setHidden:NO];
    
}


-(void)hwi08_hide_progress_bar:(UIView*)parent_view
{
    UIView *view_for_progress;
    
    for(UIView *v in [parent_view subviews])
    {
        if([v.restorationIdentifier isEqualToString:@"hwi_progress_indicator"])
        {
            view_for_progress =v;
        }
    }

    [view_for_progress setHidden:YES];
    
    
}


-(UIColor*)hwi09_getColor_with_hex_string:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    
    if ([cString length] != 6) return  [UIColor grayColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}






@end






